package com.perceptivesoftware.licensing.client.dialogs.useradmin.plugin.user;

import java.util.List;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.perceptivesoftware.licensing.client.LicensingAsyncCallback;
import com.perceptivesoftware.licensing.client.LicensingRPCFactory;
import com.perceptivesoftware.licensing.client.PerceptiveUISession;
import com.perceptivesoftware.licensing.client.common.DirtyCallbackHandler;
import com.perceptivesoftware.licensing.client.common.util.NPAction;
import com.perceptivesoftware.licensing.client.common.util.NPType;
import com.perceptivesoftware.licensing.client.common.util.PerceptivePermission;
import com.perceptivesoftware.licensing.client.dialogs.useradmin.PermissionsTreePanel;
import com.perceptivesoftware.licensing.client.dialogs.useradmin.SecurityManagerView;
import com.perceptivesoftware.licensing.client.dialogs.useradmin.callbackhandlers.DeleteCallbackHandler;
import com.perceptivesoftware.licensing.client.dialogs.useradmin.callbackhandlers.ItemSelectedCallbackHandler;
import com.perceptivesoftware.licensing.client.dialogs.useradmin.callbackhandlers.SaveCallbackHandler;
import com.perceptivesoftware.licensing.client.dialogs.useradmin.callbackhandlers.SecurityManagerAsyncCallback;
import com.perceptivesoftware.licensing.client.dialogs.useradmin.interfaces.CustomNavItemRenderer;
import com.perceptivesoftware.licensing.client.dialogs.useradmin.interfaces.Deletable;
import com.perceptivesoftware.licensing.client.dialogs.useradmin.interfaces.Saveable;
import com.perceptivesoftware.licensing.client.dialogs.useradmin.plugin.SecurityManagerNavItem;
import com.perceptivesoftware.licensing.client.dialogs.useradmin.plugin.SecurityManagerPlugin;

public class UserPlugin extends SecurityManagerPlugin<UserNavItem> implements Saveable, Deletable, CustomNavItemRenderer {

	UserView userView;
	private DirtyCallbackHandler dirtyCallbackHandler;
	private UserDTO userDTO;
	PermissionsTreePanel permissionsTreePanel;
	UserSettingsTabItem userSettingsTab;
	PerceptiveUISession session = PerceptiveUISession.getInstance();

	@Override
	public void init() {
		permissionsTreePanel = new PermissionsTreePanel(dirtyCallbackHandler, false);
		userSettingsTab = new UserSettingsTabItem(dirtyCallbackHandler);
		userView = new UserView(permissionsTreePanel, userSettingsTab);
	}

	@Override
	public String getIconStyle() {
		return "nav-icon-user";
	}

	@Override
	public SecurityManagerView getView() {
		return userView;
	}

	@Override
	protected void itemSelected(final UserNavItem ani, final ItemSelectedCallbackHandler isch) {
		if (ani.getIsSuperAdmin()) {
			userDTO = null;
			userView.hidePermissionsPanel();
			isch.doneRendering();
			LicensingRPCFactory.getSecurityService(true).getUserDTO(ani.getUserCode(), new SecurityManagerAsyncCallback<UserDTO>() {

				@Override
				public void onSuccess(final UserDTO _userDTO) {
					userDTO = _userDTO;
					userSettingsTab.setUserDto(_userDTO);
					isch.doneRendering();
				}
			});
			return;
		}
		else {
			userView.showPermissionsPanel();
			LicensingRPCFactory.getSecurityService(true).getUserDTO(ani.getUserCode(), new SecurityManagerAsyncCallback<UserDTO>() {

				@Override
				public void onSuccess(final UserDTO _userDTO) {
					userDTO = _userDTO;
					permissionsTreePanel.setPermissions(userDTO.getPermissionsDTO());
					userSettingsTab.setUserDto(_userDTO);
					isch.doneRendering();
				}
			});
		}
	}

	@Override
	public void dirtyCallbackHandler(final DirtyCallbackHandler dirtyCallbackHandler) {
		this.dirtyCallbackHandler = dirtyCallbackHandler;
	}

	@Override
	public void save(final SaveCallbackHandler sch) {
		if (userView.isUserViewVisible()) {
			final UserDTO userSettingsDTO = userSettingsTab.saveFieldsToDTO();
			userDTO.setEmail(userSettingsDTO.getEmail());
			LicensingRPCFactory.getSecurityService(true).saveUserSettings(userDTO, new LicensingAsyncCallback<UserDTO>() {

				@Override
				public void onSuccess(UserDTO dto) {
					if (userView.isSuperAdmin()) {
						sch.saved();
					}
				}

				@Override
				public void onFailure(@SuppressWarnings("unused") final Throwable caught) {
					sch.saveFailed();
				}
			});

			if (!userView.isSuperAdmin()) {
				// Window.alert("UserSavingStub");
				final List<PerceptivePermission> dirtyPermissions = userDTO.getPermissionsDTO().getDirtyPermissions();
				String whyDirty = "";
				for (final PerceptivePermission np : dirtyPermissions) {
					whyDirty += np.whyDirty();
					whyDirty += "\n";
				}

				/*
				 * if (!Window.confirm(whyDirty)) { sch.saveFailed(); return; }
				 */

				LicensingRPCFactory.getSecurityService(true).saveUserPermissions(userDTO.getUserCode(), dirtyPermissions,
						new SecurityManagerAsyncCallback<PermissionsSaveDTO>() {

							@Override
							public void onSuccess(final PermissionsSaveDTO success) {
								if (success.isSuccess()) {
									for (final PerceptivePermission np : dirtyPermissions) {
										np.savedToDatabase();
									}
									sch.saved();
									if (success.getPrompt() != null) {
										MessageBox.info("Permissions", success.getPrompt(), null);
									}
								}
								else {
									sch.saveFailed();
								}
							}

							@Override
							public void onPerceptiveFailure(final Throwable caught) {
								sch.saveFailed();
							}
						});
			}
		}
	}

	@Override
	public void delete(final SecurityManagerNavItem ani, final DeleteCallbackHandler dch) {
		final UserNavItem uni = (UserNavItem) ani;
		LicensingRPCFactory.getSecurityService(true).deleteUser(uni.getUserCode(), new SecurityManagerAsyncCallback<String>() {

			@Override
			public void onSuccess(final String failureReason) {
				if (failureReason == null) {
					dch.deleted();
				}
				else {
					dch.deleteFailed(failureReason);
				}
			}
		});
	}

	@Override
	public String getDeleteIconStyle() {
		return "nav-icon-user-delete";
	}

	@Override
	public Boolean canDelete(final SecurityManagerNavItem ani) {
		final UserNavItem uni = (UserNavItem) ani;
		if (uni.getIsSuperAdmin()) {
			return session.isSuperAdmin();
		}
		return session.hasPermission(new PerceptivePermission(NPType.ADMIN, NPAction.MANAGE_SECURITY));
	}

	@Override
	public String getCustomNavItemRenderStyle(final SecurityManagerNavItem SecurityManagerNavItem) {
		return SecurityManagerNavItem.getName();
	}

	@Override
	public String getCustomNavItemRenderText(SecurityManagerNavItem adminNavItem) {
		final UserNavItem uni = (UserNavItem) adminNavItem;
		return uni.getName();
	}
}